﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WeixinMP.Interfaces;
using System.Configuration;
using Microhard.Core.Net;
using System.ServiceModel.Dispatcher;
using Microhard.WeixinMP.Models;
using System.Web;
using Microhard.Core;

namespace Microhard.WeixinMP.Impls
{
    public class WXMPAuthInterfaceImpl : IWXMPAuthInterface
    {
        private string customerUrl = ConfigurationManager.AppSettings["CustomMsgUrl"];

        public void SendTXTCustomerMessage(string openID, string access_token, string message)
        {
            if (string.IsNullOrEmpty(openID))
                return;
            if (string.IsNullOrEmpty(access_token))
                return;
            if (string.IsNullOrEmpty(message))
                return;
            string url = customerUrl + access_token;
            string format = "{\"touser\":\"{0}\",\"msgtype\":\"text\",\"text\":{\"content\":\"{1}\"}}";
            HttpReader.HttpPost(url, string.Format(format, openID, message));
        }

        public void SendImageCustomerMessage(string openID, string access_token, string media_id)
        {
            if (string.IsNullOrEmpty(openID))
                return;
            if (string.IsNullOrEmpty(access_token))
                return;
            if (string.IsNullOrEmpty(media_id))
                return;
            string format = "{\"touser\":\"{0}\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"{1}\"}}";
            string url = customerUrl + access_token;
            HttpReader.HttpPost(url, string.Format(format, openID, media_id));
        }

        public void SendVideoCustomerMessage(string openID, string access_token, string media_id, string title, string description)
        {
            if (string.IsNullOrEmpty(openID))
                return;
            if (string.IsNullOrEmpty(access_token))
                return;
            if (string.IsNullOrEmpty(media_id))
                return;
            string format = "{\"touser\":\"{0}\",\"msgtype\":\"video\",\"video\":{\"media_id\":\"{1}\",\"title\":\"{2}\",\"description\":\"{3}\"}}";
            string url = customerUrl + access_token;
            HttpReader.HttpPost(url, string.Format(format, openID, media_id, title, description));
        }

        public byte[] DownloadMedia(string access_token, string mediaID, out string fileType)
        {
            string url = ConfigurationManager.AppSettings["GetMediaUrl"];
            url += string.Format("access_token={0}&media_id={1}", access_token, mediaID);
            fileType = string.Empty;
            return HttpReader.HttpGet(url, out fileType);
        }


        public Models.WeixinUserInfo GetUserInfo(string openID, string access_token, bool usingOnAuthUrl)
        {
            string url;
            if (usingOnAuthUrl)
            {
                //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
                url = ConfigurationManager.AppSettings["OnAuthGetUserInfo"];
                url += string.Format("access_token={0}&openid={1}&lang=zh_CN", access_token, openID);
            }
            else
            {
                //https://api.weixin.qq.com/cgi-bin/user/info?
                url = ConfigurationManager.AppSettings["GetUserInfoUrl"];
                url += string.Format("access_token={0}&openid={1}", access_token, openID);
            }
            Log.Info("GetUserInfo", url);
            string htmlResult = HttpReader.HttpGet(url);
            Log.Info("GetUserInfo", "OpenID:" + openID + " Html:" + htmlResult);
            JsonQueryStringConverter jqsv = new JsonQueryStringConverter();
            return (WeixinUserInfo)jqsv.ConvertStringToValue(htmlResult, typeof(WeixinUserInfo));
        }


        public string GetAllSubscribers(string access_token)
        {
            string url = ConfigurationManager.AppSettings["GetSubscriberUrl"];
            url += access_token;
            return HttpReader.HttpGet(url);
        }


        public WeixinErrorJSONModel CreateMenu(string access_token, string menuJson)
        {
            string url = ConfigurationManager.AppSettings["CreateMenuUrl"];
            url += access_token;
            string html = HttpReader.HttpPostWithUTF8(url, menuJson);
            JsonQueryStringConverter jqsv = new JsonQueryStringConverter();
            return (WeixinErrorJSONModel)jqsv.ConvertStringToValue(html, typeof(WeixinErrorJSONModel));
        }

        public WeixinErrorJSONModel DeleteMenu(string access_token)
        {
            string url = ConfigurationManager.AppSettings["DeleteMenuUrl"];
            url += access_token;
            string html = HttpReader.HttpGet(url);
            JsonQueryStringConverter jqsv = new JsonQueryStringConverter();
            return (WeixinErrorJSONModel)jqsv.ConvertStringToValue(html, typeof(WeixinErrorJSONModel));
        }


        public WeixinMenuModel GetMenu(string access_token, out string html)
        {
            string url = ConfigurationManager.AppSettings["GetMenuUrl"];
            url += access_token;
            html = HttpReader.HttpGet(url);
            if (!string.IsNullOrEmpty(html))
            {
                JsonQueryStringConverter jqsv = new JsonQueryStringConverter();
                return (WeixinMenuModel)jqsv.ConvertStringToValue(html, typeof(WeixinMenuModel));
            }
            return new WeixinMenuModel();
        }


        public WXMPCodeToTokenModel GetCodeToToken(Guid cmpID, string code, string state, out Guid companyId, out string companyName)
        {
            //通过wxmpid获得appid以及secret
            IWXMPAccount mpa = new WXMPAccountImpl();
            var mp = mpa.GetModelByCompanyID(cmpID);
            companyId = Guid.Empty;
            companyName = string.Empty;
            if (mp == null)
                return null;
            companyId = mp.CompanyID;
            companyName = mp.CompanyName;
            //得到通过code换取token的url
            string parms = ConfigurationManager.AppSettings["OnAuthCodeGetToken"] + "?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
            string url = string.Format(parms, mp.AppID, mp.AppSecret, code);
            string json = HttpReader.HttpGet(url);
            Log.Info("GetCodeToToken", json);
            if (!string.IsNullOrEmpty(json))
            {
                JsonQueryStringConverter jqsv = new JsonQueryStringConverter();
                return (WXMPCodeToTokenModel)jqsv.ConvertStringToValue(json, typeof(WXMPCodeToTokenModel));
            }
            return null;
        }
    }
}
